package com.varian.service.exception.handler;

import cn.hutool.core.util.StrUtil;
import com.varian.tool.contant.ResultConstant;
import com.varian.tool.result.IR;
import com.varian.tool.result.R;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;

/**
 * @author ben
 * @since 2024/7/5
 */
public class MethodArgumentNotValidExceptionHandler implements ExceptionHandlerStrategy {
    @Override
    public Class<? extends Exception> getExceptionClass() {
        return MethodArgumentNotValidException.class;
    }

    @Override
    public IR handle(Exception exception, HttpServletResponse response) {
        MethodArgumentNotValidException methodArgumentNotValidException = (MethodArgumentNotValidException) exception;
        FieldError fieldError = methodArgumentNotValidException.getBindingResult().getFieldError();
        String message = StrUtil.emptyToDefault(fieldError.getDefaultMessage(), StrUtil.format("无效参数: {}", fieldError.getField()));
        return R.fail(ResultConstant.FAIL_CODE, message);
    }
}
